const HOST = require('../../config.js').host
let app = getApp()

Page({
    data: {
        bannerHeight: '420',
        // mainImageHeight: '',
        // galleryImageHeight: '',
        bannerImages: [],
        current:0,
        activeIndex: 0,
        sliderOffset: 0,
        sliderLeft: 0,
        gallery: [{}, {}, {}, {},{}],
        _gallery: [],
        tabIcon:{
          images:[
            '../../assets/images/tuijian_', 
            '../../assets/images/weidao_',
            '../../assets/images/chaoping_',
            '../../assets/images/jiaju_',
            '../../assets/images/piaowu_'],
          text:[
            '推荐',
            '西湖味道',
            '年轻潮品',
            '生活家居',
            '票务'
          ]

        }
    },

    /**
     * 分享
     */
    onShareAppMessage () {
        return {
            title: '西湖礼物',
            path: '/pages/home/home'
        }
    },
  sendFormId(e){
    console.log(e)
    wx.request({
      url: `${HOST}v1/formid/saveFormId` ,
      method:'POST',
      data: {
        userId: app.userId,
        formId: e.detail.formId
      },
      success: res => {
        console.log(res, '插入')
      }
    })
  },
  bindchange (e)
  {
    this.setData({
      current:e.detail.current
    })
  },
  getTicket(){
    wx.navigateTo({
      url: `../getTicket/getTicket?userId=${app.userId}`,
    })
  }
  ,
  getActiveShoppingList(bannerId) {
    // console.log(this.data.isHaveCoupons);
    let self = this;
    let prdId = '';
    wx.request({
      url: HOST + 'v1/banner/toProductDetail/' + bannerId,
      method: 'GET',
      success: function (res) {
        console.log(res)
        prdId = res.data.data.id;
        wx.navigateTo({
          url: `../detail/detail?id=${ prdId }`,
        })
      }
    })
    
  }
  ,

  bannerTap (){
    let self = this;
    
    let current = this.data.current; //获取当前 banner 下标
    let obj = this.data.bannerImages[current]; //获取当前 banner 的 bannerId
    console.log(obj)
    if (obj.bannerType == "5") {
      return wx.navigateTo({
        url: `../giftGame/giftGame`,
      })
    } 
    if (obj.bannerType == "6") {
      self.getActiveShoppingList(obj.id)
      return;
    } 

      wx.navigateTo({
        url: `../bannerProList/bannerProList?id=${obj.id}&bannerName=${obj.bannerName}&bannerType=${obj.bannerType}` ,
      })


    // wx.navigateTo({
    //   url: `../giftGame/giftGame?companyId=abc&companyKey=efg`,
    // })

    // }
    // if (bannerId == "8a9d450a5c8354bc015c9f4f46540008") {
      // wx.navigateTo({
      //   url: `../graduate/graduate?bannerId=${bannerId}`
      // })
    // }
  },


    onLoadBannerImage (e) {
        this.setData({
            bannerHeight: e.detail.height
        })
    },

    tabClick: function (e) {
        let id = parseInt(e.currentTarget.id)
        let idx = e.currentTarget.dataset.idx
        let curTarget = e.currentTarget

        this.setData({
            'sliderOffset': curTarget.offsetLeft,
            // sliderLeft: this.data.padLeft,
            'activeIndex': idx
        });

        this.setGallery(idx)
    },

    /**
     * 查看商品详情
     */
    showDetail (e) {
        wx.navigateTo({
          url: `../detail/detail?id=${e.currentTarget.dataset.id}`
        })
    },

    /** 网络请求 **/
    getBanners () {
        let self = this
        wx.request({
            url: HOST + 'v1/banner/getList',
            method: 'GET',
            success (res) {
                if (res.data.sysCode === 1) {
                  console.log(res.length);
                    self.setData({
                        bannerImages: res.data.data
                    })
                }
            }
        })
    },

    /**
     * 获取全部商品数据
     */
    getGallerys () {
        // 数量需要人工修改
        for (let i = 0; i < 5; i++) {
            this.getGallery(i + 1, i);
        }
    },

    /**
     * 获取栏商品数据
     */
    getGallery (category, idx) {
        wx.request({
            url: HOST + 'v1/product/getListByType/' + category,
            method: 'GET', 
            success: function(res){
                if (res.data.sysCode === 1) {
                    let arr = res.data.data
                    console.log(res)
                    if (arr.length) {
                        let gallery = this.data.gallery || []
                        let _gallery = this.data._gallery || []
                        gallery[idx] = {}
                        _gallery[idx] = {}
                        _gallery[idx].allgoods = arr
                        // console.log(arr)
                        let str = []

                        // 取第一张图片
                        // for(let i = 0 ; i< arr.length ; i++){
                        //   str = _gallery[idx].allgoods[i].portalImg.split(",")[0]
                        //   _gallery[idx].allgoods[i].portalImg = str
                        //   // console.log(str)
                        // }
                        
                        // _gallery[idx].galleryItems = arr.slice(0, 2)
                        // _gallery[idx].galleryImages = arr.slice(2)

                        // 验证产品名是否过长
                        // let regExp = /\（.+\）$/
                        _gallery[idx].allgoods.forEach(item => {
                            if ([...item.productName].length > 12) {
                                item.productName = item.productName.slice(0, 12) + '...'
                            }
                        })
                        
                        // 指定最开始加载的页面
                        if (idx === this.data.activeIndex) {
                            gallery[idx] = _gallery[idx]
                        }

                        // console.log(gallery,_gallery)
                        this.setData({
                            gallery,
                            _gallery
                        });

                        // 需要人工调整，当第四组数据获取成功时，取消下拉刷新动画
                        if (idx === 4) {
                            wx.stopPullDownRefresh();                          
                        }
                    }
                }
            }.bind(this)
        })
    },

    setGallery (idx) {
        let gallery = this.data.gallery
        !gallery[idx].galleryItems 
        && (gallery[idx] = this.data._gallery[idx])
        this.setData({
            gallery
        })
    },

    getTabs () {
        let self = this
        let len = 0
        wx.request({
            url: HOST + 'v1/dictionary/getListByType/0/productType',
            method: 'GET', 
            success: res=>{
                if (res.data.sysCode === 1) {
                    len =res.data.data.length
                    // console.log(len)
                    self.setData({
                        tabs: res.data.data
                    })
                    // console.log(res)
                }
            }
        })
    },

    /** 生命周期 **/
    onLoad (options) {
        let that = this;
        wx.getSystemInfo({
            success: function(res) {
                that.setData({
                    sliderLeft: res.windowWidth / 75 * 2
                });
            }
        });

        this.getBanners();
        this.getGallerys();
        this.getTabs();

        // 记录带参数二维码参数
        let qrcode = {};
        if (options.store) {
            qrcode.key = '50948b19-67b8-42ff-b857-dbd35295b89s';
            qrcode.value = options.store;
        } else if (options.location) {
            qrcode.key = '50948b19-67b8-42ff-b857-dbd35295b83s';
            qrcode.value = options.location;
        } else {
            options.key && (qrcode.key = options.key);
            options.value && (qrcode.value = options.value);
        }

        // 将二维码存放于 App 中
        // app.globalData.qrcode = qrcode;

        // 将二维码存放于 storage 中
        if (qrcode.key && qrcode.value) {
            wx.setStorage({
                key: 'qrcode',
                data: qrcode,
                success () {
                    console.log('更新二维码参数成功！');
                },
                fail () {
                    console.log('更新二维码参数失败！');
                }
            })
        }
    },

    onPullDownRefresh () {
        this.getGallerys();        
    }
})
